import modelExtend from 'dva-model-extend'
import { lwjPageModel } from 'utils/model'
import { query, queryContracts, contractOrderDetail, deleteOrder, countContracts } from 'services/order'
import { routerRedux } from 'dva/router'
import pathToRegexp from 'path-to-regexp'
import { menusData } from 'utils/enumConfig'
import { Modal } from 'antd'

export default modelExtend(lwjPageModel, {
  namespace: 'orderList',
  state: {
    addModal: false,
    cancelModal: false,
    itemId: '',
    sureId: '',
    orderType: 1,
    isExpand: false,
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
    queryParam: {},
    listState: '',
    selectedTags: [],
    isShowContractDetailModal: false,
    currentContractDetail: {},
    currentListType: "salesOrder",
    countContracts: {},
    tagQueryParam:{},
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        const match = pathToRegexp('/orderList/:state').exec(pathname);
        if (match) {
          let state = match[1];
          let status = menusData[state];
          dispatch({
            type: 'saveListState', payload: {
              state
            }
          })
          dispatch({
            type: 'resetSelectedTags'
          })
          dispatch({
            type: 'setTagQueryParam',
            payload:{}
          })
          if(state==="myOrder") {
            dispatch({
              type: 'countContracts'
            })
          }
          if (state === "CANCEL") {
            dispatch({
              type: 'query',
              payload: {
                ...status,
                cancelStatus: "CANCELLED_ORDER"
              }
            })
          } else {
            dispatch({
              type: 'query',
              payload: {
                ...status
              }
            })
          }
        }
      })
    }

  },
  effects: {
    * query({
      payload
    }, { call, put, select }) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      });
      const queryParam = yield select(({ orderList }) => orderList.queryParam);
      const pageOptions = yield select(({ orderList }) => orderList.pageOptions);
      const currentListType = yield select(({ orderList }) => orderList.currentListType);
      const tagQueryParam = yield select(({ orderList }) => orderList.tagQueryParam);
      const queryPayload = {
        ...pageOptions,
        queryParam: {
          ...queryParam,
          ...tagQueryParam
        }
      };
      let data = {};
      if (currentListType === "contract") {
        data = yield call(queryContracts, queryPayload);
      } else {
        data = yield call(query, queryPayload);
      }
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      });
    },

    * onShowDetail({
      payload
    }, { select, call, put }) {
      yield put(routerRedux.push(`/orderList/detail/${payload.record.id}`, { status: payload.record.status }));
    },
    /**
     * 显示合同订单详情
     */
    * onShowContractDetail({
      payload
    }, { select, call, put }) {
      const data = yield call(contractOrderDetail, payload.salesOrderId, payload.contractOrderId);
      yield put({
        type: 'resetContractDetail'
      })
      yield put({
        type: 'detailSuccess',
        payload: {
          currentContractDetail: data.result
        }
      })
      yield put({ type: 'showContractDetailModal', payload: {} })
    },

    /**
     * 根据状态标签查询
     * @param {*} param0
     * @param {*} param1
     */
    * queryBySelectedTags({
      payload
    }, { select, call, put }) {
      const queryParam = yield select(({ orderList }) => orderList.queryParam);
      queryParam.start = 0;
      if (payload.selectedTags.length > 0) {
        if (payload.selectedTags[0].indexOf("_NO_NEED") > -1) {
          payload.selectedTags[0] = payload.selectedTags[0].substring(0, payload.selectedTags[0].indexOf("_NO_NEED"))
          queryParam.designNeeded = false;
        } else if (payload.selectedTags[0].indexOf("_NEED") > -1) {
          payload.selectedTags[0] = payload.selectedTags[0].substring(0, payload.selectedTags[0].indexOf("_NEED"))
          queryParam.designNeeded = true;
        } else {
          delete queryParam.designNeeded;
        }
      } else {
        delete queryParam.designNeeded;
      }

      yield put({
        type: 'setTagQueryParam',
        payload: {
          contractStatus: payload.selectedTags,
          designNeeded:queryParam.designNeeded
        }
      });

      yield put({
        type: 'query',
        payload: {
          // "contractStatus": payload.selectedTags,
          ...queryParam
        }
      });
      yield put({
        type: 'changeSelectedTags',
        payload: {
          selectedTags: payload.selectedTags
        }
      });


    },

    /**
     * 添加意向单
     */
    * toCreateSalesOrder({
      payload
    }, { select, call, put }) {
      const listState = yield select(({ orderList }) => orderList.listState);
      yield put(routerRedux.push(`/order/createSalesOrder`, { listState }));
    },
    /**
     *  编辑意向单
     */
    * toUpdateSalesOrder({
      payload
    }, { select, call, put }) {
      const listState = yield select(({ orderList }) => orderList.listState);
      yield put(routerRedux.push(`/order/updateSalesOrder/${payload.salesOrderId}`, { listState }));
    },
    /**
     *  编辑合同订单
     */
    * toUpdateContractOrder({
      payload
    }, { select, call, put }) {
      const listState = yield select(({ orderList }) => orderList.listState);
      yield put(routerRedux.push(`/order/updateContractOrder/${payload.salesOrderId}`, { listState }));
    },
    /**
     * 删除意向单
     */
    * deleteOrder({
      payload
    }, { select, call, put }) {
      yield call(deleteOrder, payload.salesOrderId);
      yield put({ type: 'query', payload: {} });
      Modal.success({ title: '意向订单删除成功' });
    },
    * countContracts({
      payload
    }, { select, call, put }) {
      const data = yield call(countContracts);
      yield put({ type: 'setCountContracts', payload: data.result });
    }
  },
  reducers: {
    showAddModal(state, { payload }) {
      return {
        ...state,
        addModal: true
      }
    },
    hideAddModal(state, { payload }) {
      return {
        ...state,
        addModal: false
      }
    },
    changeOrderType(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    expandFilter(state, { payload }) {
      return {
        ...state,
        isExpand: true
      }
    },
    unExpandFilter(state, { payload }) {
      return {
        ...state,
        isExpand: false
      }
    },
    showCancelModal(state, { payload }) {
      return {
        ...state,
        cancelModal: true,
        ...payload
      }
    },
    hideCancelModal(state, { payload }) {
      return {
        ...state,
        cancelModal: false
      }
    },
    saveListState(state, { payload }) {
      return {
        ...state,
        listState: payload.state
      }
    },
    changeSelectedTags(state, { payload }) {
      return {
        ...state,
        selectedTags: payload.selectedTags
      }
    },
    detailSuccess(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    showContractDetailModal(state, { payload }) {
      return {
        ...state,
        ...payload,
        isShowContractDetailModal: true
      }
    },
    hideContractDetailModal(state, { payload }) {
      return {
        ...state,
        ...payload,
        isShowContractDetailModal: false
      }
    },
    resetContractDetail(state, { payload }) {
      return {
        ...state,
        ...payload,
        currentContractDetail: {}
      }
    },
    resetSelectedTags(state, { payload }) {
      return {
        ...state,
        ...payload,
        selectedTags: []
      }
    },
    setCurrentShowList(state, { payload }) {
      return {
        ...state,
        ...payload,
        currentListType: payload
      }
    },
    setCountContracts(state, { payload }) {
      return {
        ...state,
        ...payload,
        countContracts: payload
      }
    },
    setTagQueryParam(state, { payload }) {
      return {
        ...state,
        ...payload,
        tagQueryParam: payload
      }
    },

  }
})
